﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using DynCMS.NET.Core.Entities;
using DynCMS.NET.Core.Interfaces;
using DynCMS.NET.Core.Routing;
using DynCMS.NET.Infrastructure.IOC;
using DynCMS.NET.Web.Controllers;

namespace DynCMS.NET.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            routes.MapRoute(
                name: "CMSRoute",
                url: "{pageurl}",
                defaults: new { },
                constraints: new { pageurl = new CMSRouteConstraint(IOCProvider.Instance.Resolve<IDataRepository<Page>>()) }
                );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

        protected void Application_Start()
        {
            Infrastructure.IOC.IOCProvider.Instance.Initialize();

            //DependencyResolver.SetResolver(Infrastructure.IOC.IOCProvider.Instance.Resolve<IDependencyResolver>());
            //ControllerBuilder.Current.SetControllerFactory(Infrastructure.IOC.IOCProvider.Instance.Resolve<IControllerFactory>());
            Infrastructure.IOC.IOCProvider.Instance.Register<CMSController, CMSController>("CMS");
            //Infrastructure.IOC.IOCProvider.Instance.RegisterAllFromAssemblyContaining<MvcApplication>();

            AreaRegistration.RegisterAllAreas();
            // Use LocalDB for Entity Framework by default
            //Database.DefaultConnectionFactory = new SqlConnectionFactory("Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            //BundleTable.Bundles.RegisterTemplateBundles();
        }
    }
}